﻿using System;
using System.Web.Mvc;
using Toolkit.Web.ViewComponents;
using Toolkit.Web.ViewComponents.Notification;

namespace Toolkit.Web.Mvc.ViewComponents.Notification
{
    public static class NotificationExtensions
    {
        public static NotificationBuilder NotificationValidationMessage(this ViewComponentFactory viewComponentFactory, ViewDataDictionary viewData, params string[] modelStateKeys)
        {
            return NotificationValidationMessage(viewComponentFactory, viewData, null, modelStateKeys);
        }

        public static NotificationBuilder NotificationValidationMessage(this ViewComponentFactory viewComponentFactory, ViewDataDictionary viewData, object htmlAttributes, params string[] modelStateKeys)
        {
            if (viewData == null)
            {
                throw new ArgumentNullException();
            }

            if (modelStateKeys == null)
            {
                throw new ArgumentNullException();
            }

            NotificationBuilder builder = viewComponentFactory.Notification(NotificationType.Error, htmlAttributes);

            builder.HideNotificationIfThereAreNoMessages(true);

            foreach (string key in modelStateKeys)
            {
                if (!viewData.ModelState.IsValidField(key))
                {
                    foreach (ModelError modelError in viewData.ModelState[key].Errors)
                    {
                        builder.AddMessage(modelError.ErrorMessage);
                    }
                }
            }

            return builder;
        }
    }
}
